/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ineatconseil.yougo.wicket.dao;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.ineatconseil.yougo.ws.rs.impl.provider.ContextResolver;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import javax.ws.rs.core.MediaType;

/**
 *
 * @author nicolasger
 */
public abstract class GenericDao {

	private static Client client;

	protected void initClient(String login, String password) {
		ClientConfig cc = new DefaultClientConfig();
		cc.getClasses().add(ContextResolver.class);
		client = Client.create(cc);
		client.addFilter(new LoggingFilter());
		client.addFilter(new HTTPBasicAuthFilter(login, password));
	}

	protected WebResource getResource(String relativeUrl) {
		String url = String.format("http://yougo.ineat.fr/yougo-rest/api/", 9797);
		String realUrl = url + relativeUrl;
		return client.resource(realUrl);
	}

	/**
	 * Implementation of GET method.
	 * 
	 * @param <T>
	 *            The type of object to get.
	 * @param paths
	 *            Paths for complete URL construction.
	 * @param genericType
	 *            The class of objet to get.
	 * @return A valid bean.
	 * @throws RestServiceException
	 */
	@SuppressWarnings("unchecked")
	public <T> T call(String path, GenericType<?> genericType) {

		WebResource wr = getResource(getRelativeUrl());
		if(path != null)
			wr = wr.path(path);

		// Validation du code retour
		ClientResponse cr = wr.get(ClientResponse.class);
		if (ClientResponse.Status.OK.equals(cr.getClientResponseStatus())) {
			// Validation de l'entité contenue dans la réponse
			return (T) wr.accept(MediaType.APPLICATION_JSON_TYPE).get(genericType);
		} else {
			throw new RuntimeException(cr.getClientResponseStatus().getReasonPhrase());
		}
	}

	protected abstract String getRelativeUrl();
}
